/*通用Function类
Created on 2020年05月10日
@author: zxyong 13738196011
 */

package com.zxy.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import net.sf.json.JSONSerializer;
import net.sf.json.xml.XMLSerializer;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.json.JSONObject;

public class Com_Fun
{
	public static String Http_Post(String url_path,String strCon)
	{
		String strResult = "";
		OutputStream out = null;
		BufferedReader in = null;
		HttpURLConnection conn = null;
		try
		{
			URL realUrl = new URL(url_path);
			conn = (HttpURLConnection)realUrl.openConnection();
			conn.setRequestProperty("accept","*/*");
			conn.setRequestProperty("connection","Keep-Alive");
			conn.setRequestProperty("user-agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
			conn.setRequestProperty("content-type","text/html;charset=UTF-8");
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = conn.getOutputStream();
			out.write(strCon.getBytes("UTF-8"));
			out.flush();
			int resultCode = conn.getResponseCode();
			if(HttpURLConnection.HTTP_OK == resultCode)
			{
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				String line;
				while((line = in.readLine()) != null)
				{
					strResult += line;
				}
			}
		}
		catch(Exception e)
		{
			return strResult = "error:" + e.getMessage();
		}
		finally
		{
			try
			{
				if(out != null)
				{
					out.close();
				}
				if(in != null)
				{
					in.close();
				}
				conn.disconnect();
			}
			catch(IOException ex)
			{
			}
		}
		return strResult;
	}

	public static String getParam_value1(String param_value1)
	{
		String strResult = "";
		try
		{
			String strGRT = "";
			if(param_value1.length() > 64)
			{
				strGRT = URLDecoder.decode(param_value1,"UTF-8");
				if(strGRT.length() == 64)
					strResult = com.zxy.common.EncodeUtil.aesDecrypt(strGRT,com.zxy.common.EncodeUtil.key);
				else strResult = param_value1;
			}
			else if(param_value1.length() == 64)
			{
				strResult = com.zxy.common.EncodeUtil.aesDecrypt(param_value1,com.zxy.common.EncodeUtil.key);
			}
			else strResult = param_value1;
		}
		catch(Exception ee)
		{
			System.out.println("解密数据失败：" + ee.getMessage() + " " + param_value1);
			strResult = param_value1;
		}
		return strResult;
	}

	public static String setSconnections()
	{
		String strResult = "";
		try
		{
			strResult = com.zxy.common.EncodeUtil.aesEncrypt("1VZPMMIR00LTCAKGJI28GCGOGNYXO96G" + String.valueOf(new Date().getTime()) + "bq052@a5zgk2fj%4@02mht&pmcf#%*ep",com.zxy.common.EncodeUtil.key);
		}
		catch(Exception es)
		{
		}
		return strResult;
	}

	public static boolean flagSconnections()
	{
		if(1 == 1)
			return true;
		if(Com_Para.strSessionAva.equals(""))
			return false;
		String strF = getSconnections(Com_Para.strSessionAva);
		long lgAva = Long.valueOf(strF.substring(32,45));
		long lgTime = new Date().getTime() - lgAva;
		long lgS = 100 * 24 * 60 * 60 * 1000L;// 有效期100天
		if(lgTime < lgS)
			return true;
		else return false;
	}

	public static Object getFieldValueByName(String fieldName,Object o)
	{
		try
		{
			String firstLetter = fieldName.substring(0,1).toUpperCase();
			String getter = "get" + firstLetter + fieldName.substring(1);
			Method method = o.getClass().getMethod(getter,new Class[]{});
			Object value = method.invoke(o,new Object[]{});
			return value;
		}
		catch(Exception e)
		{
			System.out.println("属性不存在");
			return null;
		}
	}

	public static String getSconnections(String encValue)
	{
		String strResult = "";
		try
		{
			strResult = com.zxy.common.EncodeUtil.aesDecrypt(encValue,com.zxy.common.EncodeUtil.key);
		}
		catch(Exception es)
		{
		}
		return strResult;
	}

	public static int get_maxConnections(String strDriverCode)
	{
		if(strDriverCode.equals("org.sqlite.JDBC"))
			return 10;
		else return 30;
	}

	public static String NoNull(Object objTag)
	{
		if(objTag == null)
			return "";
		else return objTag.toString().trim();
	}

	// 根据session_id获取用户信息
	public static String GetSessionInfo(String session_id)
	{
		String strResult = "";
		if(Com_Para.htSession != null)
		{
			for(Map.Entry<String,Object[]> entry: Com_Para.htSession.entrySet())
			{
				Object[] objV = entry.getValue();
				if(entry.getKey().equals(session_id))
				{
					strResult = objV[0].toString();
					break;
				}
			}
		}
		return strResult;
	}

	public static String FloatToStr(float finput)
	{
		java.math.BigDecimal bg = new java.math.BigDecimal(finput);
		return bg.toString();
	}

	public static String ReplacePath(String loginName,String strValue,int iFlag,int IS_URLENCODE)
	{
		String strResult = strValue;
		if(iFlag == 1)
		{
			String strG = strValue.replaceAll("src='","src='" + Com_Para.HTTP_Path).replaceAll("src=\"","src=\'" + Com_Para.HTTP_Path).replaceAll("\"","'");
			if(strG.length() > 3)
			{
				String strAtt = strG.substring(strG.length() - 4,strG.length());
				if(strAtt.toLowerCase().equals(".jpg") || strAtt.toLowerCase().equals(".gif") || strAtt.toLowerCase().equals(".png") || strAtt.toLowerCase().equals(".bmp"))
				{
					strG = Com_Para.HTTP_Path + loginName + "/" + strG;
				}
			}
			strResult = strG;
		}
		if(IS_URLENCODE == 1)
		{
			try
			{
				strResult = Java_encode(URLEncoder.encode(strResult,Com_Para.U_CODE));
			}
			catch(UnsupportedEncodingException e)
			{
			}
		}
		return strResult;
	}

	public static String Get_New_GUID()
	{
		return java.util.UUID.randomUUID().toString().toUpperCase();
	}

	public static float Get_dot_two(float fInput)
	{
		return (float)(Math.round(fInput * 100) / 100);
	}

	public static double nextDouble(final double min,final double max)
	{
		return min + ((max - min) * new Random().nextDouble());
	}

	public static double nextInt()
	{
		int iR = Math.abs(new Random().nextInt() % 2);
		return (double)iR;
	}

	public static float Get_dot_two(String fInput)
	{
		return (float)(Math.round(Float.valueOf(fInput) * 100) / 100);
	}

	public static String DateTimeStr(String DateFormat)
	{
		return new SimpleDateFormat(DateFormat).format(new Date());
	}

	public static String DateTimeStrYYYYMMDDHHmmss(String strInput,String DateFormat)
	{
		SimpleDateFormat df = new SimpleDateFormat(DateFormat);
		Date dtREQ_TIME;
		try
		{
			dtREQ_TIME = df.parse(strInput);
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dtREQ_TIME);
		}
		catch(ParseException e)
		{
			return "1900-01-01 00:00:00";
		}
	}

	public static String DateTimeToStr(Date dtREQ_TIME) throws Exception
	{
		return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dtREQ_TIME);
	}

	public static Date StrDateTime(String DateFormat,String strInput)
	{
		Date dts = null;
		try
		{
			dts = new SimpleDateFormat(DateFormat).parse(strInput);
		}
		catch(Exception ee)
		{
			System.err.println("StrDateTime" + ee.getMessage());
		}
		return dts;
	}

	// 月份相加
	public static String stepMonth(String DateFormat,Date sourceDate,int month) throws Exception
	{
		Calendar c = Calendar.getInstance();
		c.setTime(sourceDate);
		c.add(Calendar.MONTH,month);
		return new SimpleDateFormat(DateFormat).format(c.getTime());
	}

	public static String get0X01()
	{
		byte b1[] = {0x01};
		String str1 = new String(b1);
		return str1;
	}

	public static String get0X02()
	{
		byte b2[] = {0x02};
		String str2 = new String(b2);
		return str2;
	}

	public static String GetHashTable(Hashtable<String,String> ht,String key)
	{
		String strResult = "";
		if(ht.get(key) == null)
			strResult = "";
		else strResult = ht.get(key).toString();
		return strResult;
	}

	public String byte2hex(byte[] b)
	{
		String hs = "";
		String stmp = "";
		for(int n = 0;n < b.length;n++)
		{
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if(stmp.length() == 1)
			{
				hs = hs + "0" + stmp;
			}
			else
			{
				hs = hs + stmp;
			}
		}
		return hs.toUpperCase();
	}

	public byte[] hex2byte(String hex)
	{
		byte[] ret = new byte[8];
		byte[] tmp = hex.getBytes();

		for(int i = 0;i < 8;i++)
		{
			ret[i] = uniteBytes(tmp[i * 2],tmp[i * 2 + 1]);
		}
		return ret;
	}

	public static byte uniteBytes(byte src0,byte src1)
	{
		byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
		_b0 = (byte)(_b0 << 4);
		byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
		byte ret = (byte)(_b0 ^ _b1);
		return ret;
	}

	public static JSONObject xmlToJSON(String xml)
	{
		JSONObject obj = new JSONObject();
		try
		{
			InputStream is = new ByteArrayInputStream(xml.getBytes(Com_Para.U_CODE));
			SAXBuilder sb = new SAXBuilder();
			Document doc = sb.build(is);
			Element root = doc.getRootElement();
			Map<String,Object> map = iterateElement(root);
			obj.put(root.getName(),map);
			return obj;
		}
		catch(Exception e)
		{
			return null;
		}
	}

	/**
	 * json转xml
	 */
	public static String JSONToXml(String json,String param_name)
	{
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setRootName(param_name);
		xmlSerializer.setTypeHintsEnabled(true);
		String xml = xmlSerializer.write(JSONSerializer.toJSON(json),Com_Para.U_CODE);
		return xml;
	}

	private static Map<String,Object> iterateElement(Element root)
	{
		List childrenList = root.getChildren();
		Element element = null;
		Map map = new HashMap();
		List list = null;
		for(int i = 0;i < childrenList.size();i++)
		{
			list = new ArrayList();
			element = (Element)childrenList.get(i);
			if(element.getChildren().size() > 0)
			{
				if(root.getChildren(element.getName()).size() > 1)
				{
					if(map.containsKey(element.getName()))
					{
						list = (List)map.get(element.getName());
					}
					list.add(iterateElement(element));
					map.put(element.getName(),list);
				}
				else
				{
					map.put(element.getName(),iterateElement(element));
				}
			}
			else
			{
				if(root.getChildren(element.getName()).size() > 1)
				{
					if(map.containsKey(element.getName()))
					{
						list = (List)map.get(element.getName());
					}
					list.add(element.getTextTrim());
					map.put(element.getName(),list);
				}
				else
				{
					map.put(element.getName(),element.getTextTrim());
				}
			}
		}

		return map;
	}

	public static String Java_encode(String strInput)
	{
		return strInput.replaceAll("%27","'").replaceAll("%21","!").replaceAll("%28","(").replaceAll("%29",")").replaceAll("%7E","~").replaceAll("%0D","");// .replaceAll("+","%20");
	}

	public static String GetAbsPath()
	{
		String strResult = Com_Para.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		int iLength = strResult.lastIndexOf(Com_Para.zxyPath);

		String os = System.getProperty("os.name");
		if(os.toLowerCase().startsWith("win"))
		{
			if(iLength > 0)
				return strResult.substring(1,iLength) + "/";
			else return strResult.substring(1,strResult.length()) + "/";
		}
		else
		{
			if(iLength > 0)
				return strResult.substring(0,iLength) + "/";
			else return strResult.substring(0,strResult.length()) + "/";
		}
	}

	public static String GetImgPath(String param_name)
	{
		String strReturn = "";
		if(param_name.equals("xxxxxx"))
		{
			strReturn = "temp/admin";
		}
		return strReturn;
	}

	public static boolean GetInterSession(String SQLName)
	{
		if(Com_Para.htInterSession == null)
		{
			Com_Para.htInterSession = new Hashtable<String,Integer>();

			for(String strIntS: Com_Para.InterSession.split(","))
			{
				Com_Para.htInterSession.put(strIntS,1);
			}
		}

		if(Com_Para.htInterSession.containsKey(SQLName))
			return true;
		else return false;
	}

	public static String SetSession(String temsession_id,String values)
	{
		Object[] objV = {values,new Date()};
		if(Com_Para.htSession == null)
		{
			Com_Para.htSession = new Hashtable<String,Object[]>();
			Com_Para.htSession.put(temsession_id,objV);
		}
		else
		{
			if(values.equals("") && Com_Para.htSession.containsKey(temsession_id))
				objV[0] = ((Object[])Com_Para.htSession.get(temsession_id))[0];
			Com_Para.htSession.put(temsession_id,objV);
		}
		return temsession_id;
	}

	public static boolean HadSession(String keys,String login_id)
	{
		boolean bResult = false;
		if(Com_Para.htSession == null)
		{
			Com_Para.htSession = new Hashtable<String,Object[]>();
		}
		else if(Com_Para.htSession.containsKey(keys))
		{
			Object[] objV = Com_Para.htSession.get(keys);
			Date dtSession = null;
			try
			{
				dtSession = (Date)objV[1];
				long lgTime = new Date().getTime() - dtSession.getTime();
				if(lgTime < Com_Para.SessionTimeOut * 60000)
				{
					objV[1] = dtSession;
					Com_Para.htSession.put(keys,objV);
					bResult = true;
				}
				else
				{
					Com_Para.htSession.remove(keys);
					bResult = false;
				}
			}
			catch(Exception e)
			{
			}
		}
		return bResult;
	}

	public static Document ReadXmlFile(File objF)
	{
		Document doc = null;
		try
		{
			SAXBuilder builder = new SAXBuilder();
			doc = builder.build(objF);
		}
		catch(JDOMException e)
		{
		}
		catch(IOException e)
		{
		}
		return doc;
	}
}